#!/usr/bin/env python2
import os
import sys
import errno
import uuid
import getopt
import subprocess
import time
import re

path = os.path.abspath(os.path.split(os.path.realpath(__file__))[0])
sys.path.insert(0, "%s/../admin/" %(path))

from utils import Exp, _exec_pipe, _put_remote, _exec_system, _exec_shell, _derror, _isip, _exec_remote

class Iscsi():
    def __init__(self, v):
        self.verbose = v

    def login(self, ip, tgt):
        target = ""

        res = _exec_pipe(['iscsiadm', '-m', 'discovery', '-t', 'sendtargets', '-p', ip], p=self.verbose)
        m = re.findall("iqn.*:%s"%tgt, res)
        if m:
            target = m[0]

        res = _exec_pipe(['iscsiadm', '-m', 'node', '-T', target, '-p', ip, '--login'], p=self.verbose)

    def getdev(self, tgt):
        devs = []
        lun = ""
        tag = False
        try:
            res = _exec_pipe(['iscsiadm', '-m', 'session', '-P3'], p=self.verbose)
            for line in res.splitlines():
                if line.startswith('Target:'):
                    tag = False
                    m = re.match('Target:.*:%s' % tgt, line)
                    if m:
                        tag = True
                else:
                    m = re.match("\s*scsi\d+ Channel \d+ Id \d+ Lun: (\d+)", line)
                    if m:
                        lun = m.group(1)
                    m = re.match("\s*Attached scsi disk (\w+)\s*State: running", line)
                    if m:
                        dev = m.group(1)
                        if tag:
                            devs.append((lun, dev))
        except:
            pass

        return devs

    def logout(self):
        try:
            res = _exec_pipe(['iscsiadm', '-m', 'node', '-u'], p=self.verbose)
        except:
            pass
